<?php
/**
 * @property Mailing $Mailing
 * @property User $User
 * @todo Zablokowanie możliwości logowania za pomocą hasła z pustym hasłem!
 */
class UsersController extends AppController {

    public $uses = array('User');
    public $helpers = array('Text', 'Form');
    public $components = array('Auth', 'Session');

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->deny('admin_index', 'admin_view', 'admin_add', 'admin_delete', 'admin_edit');
    }
    
    public function id(){
        $this->layout = 'login';
        $this->helpers = array('Session');
    }
    
    
    public function secretPlace() {
        $this->layout = 'login';
        print_r("You're in the secret place");
    }

    public function logout() {
        $this->layout = 'login';
        $this->Auth->logout();
        $this->Session->delete("ExtAuth");
        setcookie('loggedin', '0', 0, "/");
        $this->redirect("/");
    }
    
    public function login($extauth = NULL) {
        if(isset($this->request->query) && !empty($this->request->query['continue'])){
            $this->Session->write('Auth.redirect',$this->request->query['continue']);
        }
        
        $this->layout = 'login';
        if ($extauth != NULL && $this->Session->check("ExtAuth")) {
            $extAuthUser = $this->Session->read("ExtAuth"); 
            $user = $this->User->findByEmail($extAuthUser['email']);
           
            if (!empty($user)) {

                if (!empty($user) && $user['User']['deleted'] == 1) {
                    $this->Session->setFlash(__('Konto zostało usunięte. __Skontaktuj się__ z administratorem w celu przywrócenia konta.'));
                    return;
                }

                if ($user['User']['facebook'] == NULL && $extAuthUser['type'] == "Facebook") {
                    $this->User->id = $user['User']['id'];
                    $this->User->saveField('facebook', $extAuthUser['ext_id']);
                } else if ($user['User']['google'] == NULL && $extAuthUser['type'] == "Google") {
                    $this->User->id = $user['User']['id'];
                    $this->User->saveField('google', $extAuthUser['ext_id']);
                }

                if ($user['User']['active'] == 0) {
                    $this->User->id = $user['User']['id'];
                    $this->User->saveField('active', 1);
                }

                $this->Auth->login($user['User']);
                if($this->Session->check('Auth.redirect')){
                    $this->redirect($this->Session->read('Auth.redirect'));
                } else {
                    $this->redirect($this->Auth->redirect());
                }
            } else {
                $this->redirect(array('action' => 'register', 'extauth'));
            }
        }

        if (!empty($this->request->data)) {

            $user = $this->User->findByEmail($this->request->data['User']['email']);
           
            if ($this->request->data['register'] == 1) {
                if (!empty($user)) {
                    $this->Session->setFlash(__("Użytkownik z podanym adresem e-mail już istnieje. Zaloguj się lub __przypomnij hasło__."));
                } else {
                    $this->Session->write('register.email',$this->request->data['User']['email']);
                    $this->redirect(array('action' => 'register'));
                }
            } else {

                if (!empty($user) && $user['User']['active'] == 0) {
                    $this->Session->setFlash(__('Konto nieaktywne. Sprawdź skrzynkę mailową i kliknij w link aktywacyjny lub __wyślij maila ponownie__.'));
                    return;
                }

                if (!empty($user) && $user['User']['deleted'] == 1) {
                    $this->Session->setFlash(__('Konto zostało usunięte. __Skontaktuj się__ z administratorem w celu przywrócenia konta.'));
                    return;
                }
                //array_merge($this->request->data['User'],array('id'=>$user['User']['id']))
                if ($this->Auth->login()) {
                    if($this->Session->check('Auth.redirect')){
                        $this->redirect($this->Session->read('Auth.redirect'));
                    } else {
                        $this->redirect($this->Auth->redirect());
                    }
                } else {
                    $this->Session->setFlash(__('Nieprawidłowe hasło, spróbuj ponownie lub __przypomnij hasło__.'));
                }
            }
        }
    }

    public function register($extauth = NULL) {
        $this->layout = 'login';
        $this->set('extauth', $extauth);
        
        if(!empty($this->request->data)) {

            $newUser = array('User' => array(
                    'name' => $this->request->data['User']['name'],
                    'email' => $this->request->data['User']['email']
                    ));

            if ($extauth != NULL && $this->Session->check("ExtAuth")) {
                $extAuthUser = $this->Session->read("ExtAuth");
                $user = $this->User->findByEmail($extAuthUser['email']);

                if ($extAuthUser['type'] == "Facebook") {
                    $newUser['User']['facebook'] = $extAuthUser['ext_id'];
                } else if ($extAuthUser['type'] == "Google") {
                    $newUser['User']['google'] = $extAuthUser['ext_id'];
                }

                $newUser['User']['active'] = 1;
                $newUser['User']['link'] = $extAuthUser['link'];
            } else {
                $user = $this->User->findByEmail($this->request->data['User']['email']);
                $newUser['User']['active'] = 0;
                if ($this->request->data['User']['password'] != $this->request->data['User']['repeat_password']) {
                    $this->Session->setFlash(__('Podane hasła nie zgadzają się. Wpisz ponownie hasło.'));
                    return;
                } else {
                    $newUser['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
                }
            }

            if (!empty($user) && $user['User']['active'] == 0) {
                $this->Session->setFlash(__('Konto nieaktywne. Sprawdź skrzynkę mailową i kliknij w link aktywacyjny lub __wyślij maila ponownie__.'));
                return;
            } else if (!empty($user) && $user['User']['deleted'] == 1) {
                $this->Session->setFlash(__('Konto zostało usunięte. __Skontaktuj się__ z administratorem w celu przywrócenia konta.'));
                return;
            } else if (!empty($user)) {
                $this->Session->setFlash(__("Użytkownik z podanym adresem e-mail już istenieje. __Zaloguj się__ lub __przypomnij hasło__."));
                return;
            }
            
            if ($this->request->data['User']['agreement1'] != 1 || $this->request->data['User']['agreement2'] != 1){
                $this->Session->setFlash(__("Musisz wyrazić zgodę na regulamin i przetwarzanie danych osobowych, aby utworzyć konto w serwisie."));
                return;
            }

            if ($this->User->save($newUser)) {
                if ($newUser['User']['active'] == 0) {
                    App::uses('CakeEmail', 'Network/Email');
                    
                    
                    $email = new CakeEmail();
                    $email->template('register', 'default')
                        ->emailFormat('text')
                        ->from(array('noreply@gdgs.pl' => 'Google Developers Groups - Polska'))
                        ->to($newUser['User']['email'])
                        ->subject('Potwierdzenie rejestracji w Gdgs.pl')
                        ->viewVars(array('activate_link' => Router::url(
                                    array(
                                'controller' => 'users',
                                'action' => 'verify',
                                $this->User->id,
                                $this->generateSignature($this->User->id, $newUser['User']['email'], $newUser['User']['name'])
                                    ), true
                            )))
                        ->send();
                    $this->redirect(array('controller' => 'users', 'action' => 'sentConfirmation'));
                } else {
                    $this->Auth->login($this->User);
                    $this->redirect($this->Auth->redirect());
                }
                
            }
        } else {
            if($this->Session->check("ExtAuth")) {
                $userEmail = $this->Session->read("ExtAuth.email");
            } else if($this->Session->check("register.email")){
                $userEmail = $this->Session->read('register.email');
            }
            $this->request->data['User']['email'] = $userEmail;
        }
    }
    
    public function verify($id, $sigMd5) {
        $this->layout = 'login';
        $user = $this->User->findById($id);
        if ($this->generateSignature($id, $user['User']['email'], $user['User']['name']) == substr($sigMd5, 0, 8)) {
            $this->User->id = $id;
            $this->User->saveField("active", 1);
            //$this->set("result", true);
            $this->Auth->login($user['User']);
            $this->redirect('/');
            exit();
        } else {
            $this->Session->setFlash(__("Weryfikacja niepoprawna. Upewnij się, że link z emaila jest poprawny."));
        }
    }

    
    public function sentConfirmation() {
        $this->layout = 'login';
    }
    
    private function generateSignature($id, $email, $username) {
        return substr(md5($id . $email . $username), 0, 8);
    }
    
    
    /**
     * view method
     *
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }
    
    public function mailing($type=null, $sig=null, $passEmail=null){
        
        if(!$type){
            throw new NotFoundException(__('Unknown action'));
        }
        if($type == 'set'){
            $email = !empty($this->request->data['Mailing']['email']) ? $this->request->data['Mailing']['email'] : null;
            if(empty($email)){
                throw new NotFoundException(__('Unknown email'));
            }
            $sendConfirmation = true;
            $this->loadModel('Mailing');
            
            $data = $this->Mailing->findByEmail($email);
            if($data){
                throw new BadRequestException(__('Podany email już jest dopisany do bazy mailingowej.',402));
            }
            
            
            if($this->Auth->user('id')!=null){
                $this->request->data['Mailing']['user_id'] = $this->Auth->user('id');
                $this->request->data['Mailing']['active'] = 1;
                $sendConfirmation = false;
            }
            
            $this->Mailing->create();
            if($this->Mailing->save($this->request->data)){
                //
                // SEND CONFIRMATION if not user
                //
                if($sendConfirmation){
                    App::uses('CakeEmail', 'Network/Email');
                    
                    $_email = new CakeEmail();
                    $_email->template('mailing_set', 'default')
                        ->emailFormat('text')
                        ->from('noreply@gdgs.pl', 'Google Developers Groups - Polska')
                        ->to($email)
                        ->subject('Potwierdzenie subskrypcji gdgs.pl')
                        ->viewVars(array('activate_link' => Router::url(array(
                            'controller' => 'users',
                            'action' => 'mailing',
                            'verify',
                            $this->generateSignature('mailing', $email, 'set'),
                            $email
                        ), true)))
                        ->send();
                }
                $this->set('result',array('active'=>!$sendConfirmation));
            } else {
                
                $this->set('result',$this->Mailing->validationErrors);
            }
        } else if($type == 'remove'){
        } else if($type == 'verify'){  
            if(!empty($sig) && !empty($passEmail)){
                if ($this->generateSignature('mailing', $passEmail, 'set') == substr($sig, 0, 8)) {
                    $this->loadModel('Mailing');
                    $data = $this->Mailing->findByEmail($passEmail);
                    if(!$data){
                        throw new NotFoundException(__('Unknown record. Try again.'));
                    }
                    $this->Mailing->id = $data['Mailing']['id'];
                    $this->Mailing->saveField("active", 1);
                    $this->render('mailing_verified');
                } else {
                    throw new NotFoundException(__('Invalid signature'));
                }
            } else {
                throw new NotFoundException(__('Unknown params'));
            }
        } else {
            throw new NotFoundException(__('Unknown action'));
        }
    }
    
    
    
    /**
     * admin_index method
     *
     * @return void
     */
    public function admin_index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    /**
     * admin_view method
     *
     * @param string $id
     * @return void
     */
    public function admin_view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
        $chapters = $this->User->Chapter->find('list');
        $this->set(compact('chapters'));
    }

    /**
     * admin_edit method
     *
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
        $chapters = $this->User->Chapter->find('list');
        $this->set(compact('chapters'));
    }

    /**
     * admin_delete method
     *
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
    
}

?>